<template>
  <van-button :loading="loading" v-if="isFollowed" class="follow-btn" round size="small" @click="onFollow">已关注</van-button>
  <van-button :loading="loading" v-else class="follow-btn" type="info" color="#3296fa" round size="small" icon="plus" @click="onFollow">关注</van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/users.js'
export default {
  name: 'FollowUser',
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [String, Number, Object],
      required: true
    }
  },
  data() {
    return {
      loading: false
    }
  },
  methods: {
    async onFollow() {
      this.loading = true // 用户点击按钮 让它处于loading状态  等请求玩数据 不管是成功还是失败 都结束loading
      try {
        if (this.isFollowed) {
          await deleteFollow(this.userId)

          // 已关注
        } else {
          // 没有关注
          await addFollow(this.userId)
        }
        this.$emit('update-is_followed', !this.isFollowed)
      } catch (err) {
        let msg = '操作失败，请重试'
        if (err.response && err.response.status === 400) {
          msg = '不能关注自己'
        }
        this.$toast(msg)
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
